
#import "MyGameAppDelegate.h"

@implementation MyGameAppDelegate

@synthesize window = _window;

// Note: You can ignore the Xcode console message "Application windows are expected to have a root view controller
// at the end of application launch". For simplicity most game projects in this book consist only of a single view.
// However, you can easily add a ViewController if you need it. See e.g. the GameKit or the GLKitBasics examples.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];   
    mainView = [[MainView alloc] initWithFrame: [UIScreen mainScreen].applicationFrame];
	mainView.backgroundColor = [UIColor grayColor];	
    [self.window addSubview: mainView];
    [self.window makeKeyAndVisible];      
    return YES;
}

- (void) startGameLoop {    
    NSString *deviceOS = [[UIDevice currentDevice] systemVersion];    
    bool forceTimerVariant = TRUE;
    
    if (forceTimerVariant || [deviceOS compare: @"3.1" options: NSNumericSearch] == NSOrderedAscending) {
        //33 frames per second -> timestep between the frames = 1/33    
        NSTimeInterval fpsDelta = 0.0303;
        timer = [NSTimer scheduledTimerWithTimeInterval: fpsDelta
                                                 target: self
                                               selector: @selector( loop )
                                               userInfo: nil
                                                repeats: YES]; 
        
    } else {
        int frameLink = 2;
        timer = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget: self selector: @selector( loop )];
        [timer setFrameInterval: frameLink];
        [timer addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
    }
    
    NSLog(@"Game Loop timer instance: %@", timer);   
}

- (void) stopGameLoop {
    [timer invalidate];
    timer = nil;
}

- (void) loop {
	[mainView setNeedsDisplay]; //triggers MainView's drawRect:-method	
}

- (void) applicationDidBecomeActive: (UIApplication *) application {
    [self startGameLoop];
}

- (void) applicationWillResignActive: (UIApplication *) application {
    [self stopGameLoop];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {}
- (void)applicationWillEnterForeground:(UIApplication *)application {}
- (void)applicationWillTerminate:(UIApplication *)application {}

- (void) dealloc {
    [self stopGameLoop];
    [timer release];
    [_window release];
    [mainView release];
    [super dealloc];
}

@end
